<template>
  <div class="article-comments">
    <!-- 评论列表 -->
    <van-list v-model="loading" :finished="finished" finished-text="没有更多了" @load="onLoad" :error.sync="error"
      error-text="请求失败，点击重新加载">
      <!-- 评论 -->
      <commentitem :comment="item" v-for="item in list" :key="item.com_id+''" />
    </van-list>
    <!-- 评论列表 -->

    <!-- 发布评论 -->
    <van-cell-group class="publish-wrap">
      <van-field clearable placeholder="请输入评论内容">
        <van-button slot="button" size="mini" type="info">发布</van-button>
      </van-field>
    </van-cell-group>
    <!-- /发布评论 -->
  </div>
</template>

<script>
import { getCommentList } from '@/api/comment.js'
import commentitem from './commentitem.vue'
export default {
  name: 'ArticleComment',
  components: {
    commentitem
  },
  props: {
    // 获取评论
    type: {
      type: String,
      default: 'a'
    },
    // 文章id
    source: {
      type: [Object, String],
      required: true
    }
  },
  data () {
    return {
      list: [], // 评论列表
      loading: false, // 上拉加载更多的 loading
      finished: false, // 是否加载结束
      offset: null, // 页码
      limit: 10, // 每条数据
      total_count: 0,
      error: false
    }
  },
  created () {
    console.log(this.type)
    console.log(this.limit)
  },
  methods: {
    async onLoad () {
      // 1 发请求获取数据
      try {
        const { data: res } = await getCommentList({
          type: this.type,
          limit: this.limit,
          source: this.source + '',
          offset: this.offset
        })
        // 2 保存数据
        console.log(res)
        this.list.push(...res.data.results)
        this.total_count = res.data.total_count
        this.$emit('updateTotal', this.total_count)
        // 3 this.loading=false
        this.loading = false
        if (this.list.length === this.total_count) {
          // 没有数据了，就让他不要加载了
          this.finished = true
        } else {
          this.offset = res.data.last_id
        }
      } catch (err) {
        this.$toast('获取评论失败')
        this.error = true
      }

      // 4 数据全部加载完成
      // 异步更新数据

      // 加载状态结束

      // 数据全部加载完成
    }
  }
}
</script>

<style scoped lang="less">
.publish-wrap {
  position: fixed;
  left: 0;
  bottom: 0;
  width: 100%;
}

.van-list {
  margin-bottom: 45px;
}
</style>
